package com.pig4cloud.pig.module.controller.farm;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.pig4cloud.pig.common.core.util.DateUtils;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.module.api.entity.farm.FarmFeedRecord;
import com.pig4cloud.pig.module.api.entity.mer.Mer;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.service.farm.IFarmFeedRecordService;
import com.pig4cloud.pig.module.service.mer.IMerService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import com.vdurmont.emoji.EmojiParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.*;

/**
 * 农场的饲料和鸡蛋的出入记录Controller
 *
 * @author ruoyi
 * @date 2022-05-14
 */
@Validated
@Api(value = "农场的饲料和鸡蛋的出入记录控制器", tags = {"农场的饲料和鸡蛋的出入记录管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/farm/feed/record")
public class FarmFeedRecordController {

    private final IFarmFeedRecordService farmFeedRecordService;
	private final IWxUserService wxUserService;
	private final IMerService merService;

    /**
     * 查询农场的饲料和鸡蛋的出入记录列表
     */
    @ApiOperation("查询农场的饲料和鸡蛋的出入记录列表")
    @PreAuthorize("@pms.hasPermission('module:feedrecord:list')")
    @GetMapping("/list")
    public TableDataInfo<FarmFeedRecord> list(@Validated FarmFeedRecord farmFeedRecord) {
        QueryWrapper<FarmFeedRecord> qw = new QueryWrapper<>();
        if(farmFeedRecord.getMerId() != null){
        	qw.eq("mer_id",farmFeedRecord.getMerId());
		}
		if(farmFeedRecord.getRecordType() != null){
			qw.eq("record_type",farmFeedRecord.getRecordType());
		}
		if(farmFeedRecord.getFromType() != null){
			qw.eq("from_type",farmFeedRecord.getFromType());
		}
		if(farmFeedRecord.getSettleRecordId() != null && farmFeedRecord.getSettleRecordId() > 0){
			qw.eq("settle_record_id",farmFeedRecord.getSettleRecordId());
		}

		if(farmFeedRecord.getIsSettle() != null){
			qw.eq("is_settle",farmFeedRecord.getIsSettle());
		}
		if(StrUtil.isNotEmpty(farmFeedRecord.getBeginDate())){
			qw.between("create_time", farmFeedRecord.getBeginDate()
				+ " 00:00:00",farmFeedRecord.getEndDate() + " 23:59:59");
		}
		qw.orderByDesc("create_time");
        TableDataInfo<FarmFeedRecord> td = PageUtils.buildDataInfo(farmFeedRecordService.page(PageUtils.buildPage(),qw));
        List<FarmFeedRecord> list = td.getData();
        if(CollUtil.isNotEmpty(list)){
        	for (FarmFeedRecord feedRecord : list){
				WxUser wxUser = wxUserService.findById(feedRecord.getUserId());
				if(wxUser!=null){
					if(StrUtil.isNotEmpty(wxUser.getNickName())){
						feedRecord.setNickName(EmojiParser.parseToUnicode(wxUser.getNickName()));
					}
				}
			}
		}
        return td;
    }


	/**
	 * 获取月度对账信息
	 */
	@ApiOperation("获取月度对账信息")
	@PreAuthorize("@pms.hasPermission('module:feedrecord:query')")
	@GetMapping("/getFeedRecordByMonth")
	public R<List<Map<String,Object>>> getBalance(@Validated FarmFeedRecord farmFeedRecord) {
		List<Map<String,Object>> dataListNew = new ArrayList<>();
		List<Map<String,Object>> dateList = new ArrayList<>();
		if(farmFeedRecord.getYear()!=null){
			dateList = DateUtils.getDateTimeByMonth(farmFeedRecord.getYear());
		}else{
			dateList = DateUtils.getDateTimeByMonth();
		}
		if(CollUtil.isNotEmpty(dateList)){
			for(int i = 0; i < dateList.size(); i++){
				Map<String,Object> map = dateList.get(i);
				String beginTime = map.get("beginDate").toString() + " 00:00:00";
				String endTime = map.get("endDate").toString() + " 23:59:59";

				System.out.println("开始时间：" + beginTime);
				System.out.println("结束时间：" + endTime);

				Map<String,Object> mapParamAll = new HashMap<>();
				mapParamAll.put("beginTime",beginTime);
				mapParamAll.put("endTime",endTime);
				mapParamAll.put("merId",farmFeedRecord.getMerId());
				mapParamAll.put("fromType",8);
				mapParamAll.put("recordType",2);
				double countAll = farmFeedRecordService.getEggCountByMerId(mapParamAll);

				map.put("countAll",countAll);

				Map<String,Object> mapParamUnSettle = new HashMap<>();
				mapParamUnSettle.put("beginTime",beginTime);
				mapParamUnSettle.put("endTime",endTime);
				mapParamUnSettle.put("merId",farmFeedRecord.getMerId());
				mapParamUnSettle.put("fromType",8);
				mapParamUnSettle.put("recordType",2);
				mapParamUnSettle.put("isSettle",0);

				double countUnSettle = farmFeedRecordService.getEggCountByMerId(mapParamUnSettle);

				map.put("countUnSettle",countUnSettle);



				Map<String,Object> mapParamSettling = new HashMap<>();
				mapParamSettling.put("beginTime",beginTime);
				mapParamSettling.put("endTime",endTime);
				mapParamSettling.put("merId",farmFeedRecord.getMerId());
				mapParamSettling.put("fromType",8);
				mapParamSettling.put("recordType",2);
				mapParamSettling.put("isSettle",1);
				double countSettling = farmFeedRecordService.getEggCountByMerId(mapParamSettling);
				map.put("countSettling",countSettling);


				Map<String,Object> mapParamSettled = new HashMap<>();
				mapParamSettled.put("beginTime",beginTime);
				mapParamSettled.put("endTime",endTime);
				mapParamSettled.put("merId",farmFeedRecord.getMerId());
				mapParamSettled.put("fromType",8);
				mapParamSettled.put("recordType",2);
				mapParamSettled.put("isSettle",2);
				double countSettled = farmFeedRecordService.getEggCountByMerId(mapParamSettled);
				map.put("countSettled",countSettled);

				map.put("merId",farmFeedRecord.getMerId());
				map.put("id",0);
				if(countAll > 0){
					dataListNew.add(map);
				}
//				dataListNew.add(map);
			}
		}
		return R.ok(dataListNew);
	}

	/**
     * 导出农场的饲料和鸡蛋的出入记录列表
     */
    @ApiOperation("导出农场的饲料和鸡蛋的出入记录列表")
    @PreAuthorize("@pms.hasPermission('module:feedrecord:export')")
    @SysLog("农场的饲料和鸡蛋的出入记录")
    @GetMapping("/export")
    public List export(@Validated FarmFeedRecord farmFeedRecord) {
		QueryWrapper<FarmFeedRecord> qw = new QueryWrapper<>();
		if(farmFeedRecord.getMerId() != null){
			qw.eq("mer_id",farmFeedRecord.getMerId());
		}
		if(farmFeedRecord.getRecordType() != null){
			qw.eq("record_type",farmFeedRecord.getRecordType());
		}
		if(farmFeedRecord.getFromType() != null){
			qw.eq("from_type",farmFeedRecord.getFromType());
		}

		if(farmFeedRecord.getIsSettle() != null){
			qw.eq("is_settle",farmFeedRecord.getIsSettle());
		}
		if(StrUtil.isNotEmpty(farmFeedRecord.getBeginDate())){
			qw.between("create_time", farmFeedRecord.getBeginDate()
				+ " 00:00:00",farmFeedRecord.getEndDate() + " 23:59:59");
		}
		qw.orderByDesc("create_time");
        List<FarmFeedRecord> list = farmFeedRecordService.list(qw);
        if(CollUtil.isNotEmpty(list)){
        	for (FarmFeedRecord feedRecord : list){
        		WxUser wxUser = wxUserService.findById(feedRecord.getUserId());
        		if(wxUser!=null){
        			if(StrUtil.isNotEmpty(wxUser.getNickName())){
						feedRecord.setNickName(EmojiParser.parseToUnicode(wxUser.getNickName()));
					}
				}
				feedRecord.setCreateDateTxt(DateUtils.getDate(feedRecord.getCreateTime()));
				feedRecord.setCreateTimeTxt(DateUtils.getSimpleTime(feedRecord.getCreateTime()));
				Mer mer = merService.getById(feedRecord.getMerId());
				if(mer!=null){
					feedRecord.setMerName(mer.getShopName());
				}
				if(feedRecord.getIsSettle() == 0){
					feedRecord.setSettleState("未结算");
				} else if(feedRecord.getIsSettle() == 1){
					feedRecord.setSettleState("已结算");
				}
			}
		}
        // ExcelUtil<FarmFeedRecord> util = new // ExcelUtil<>(FarmFeedRecord.class);
        return  list;// util.exportExcel(list, "农场的饲料和鸡蛋的出入记录");
    }

    /**
     * 获取农场的饲料和鸡蛋的出入记录详细信息
     */
    @ApiOperation("获取农场的饲料和鸡蛋的出入记录详细信息")
    @PreAuthorize("@pms.hasPermission('module:feedrecord:query')")
    @GetMapping("/{id}")
    public R<FarmFeedRecord> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        FarmFeedRecord farmFeedRecord = farmFeedRecordService.getById(id);
        return R.ok(farmFeedRecord);
    }

    /**
     * 新增农场的饲料和鸡蛋的出入记录
     */
    @ApiOperation("新增农场的饲料和鸡蛋的出入记录")
    @PreAuthorize("@pms.hasPermission('module:feedrecord:add')")
    @SysLog("农场的饲料和鸡蛋的出入记录")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody FarmFeedRecord farmFeedRecord) {
        return R.okByRow(farmFeedRecordService.save(farmFeedRecord) ? 1 : 0);
    }

    /**
     * 修改农场的饲料和鸡蛋的出入记录
     */
    @ApiOperation("修改农场的饲料和鸡蛋的出入记录")
    @PreAuthorize("@pms.hasPermission('module:feedrecord:edit')")
    @SysLog("农场的饲料和鸡蛋的出入记录")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody FarmFeedRecord farmFeedRecord) {
        return R.okByRow(farmFeedRecordService.updateById(farmFeedRecord) ? 1 : 0);
    }

    /**
     * 删除农场的饲料和鸡蛋的出入记录
     */
    @ApiOperation("删除农场的饲料和鸡蛋的出入记录")
    @PreAuthorize("@pms.hasPermission('module:feedrecord:remove')")
    @SysLog("农场的饲料和鸡蛋的出入记录")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(farmFeedRecordService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }


	/**
	 *  批量修改结算状态
	 */
	@ApiOperation("批量修改结算状态")
	@PreAuthorize("@pms.hasPermission('module:feedrecord:remove')")
	@SysLog("批量修改结算状态")
	@DeleteMapping("/batchSettle/{ids}")
	public R<Void> batchSettle(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
		 boolean bl = farmFeedRecordService.update(new LambdaUpdateWrapper<FarmFeedRecord>()
			.set(FarmFeedRecord::getIsSettle, 1)
			.in(FarmFeedRecord::getId, Arrays.asList(ids)));
		return R.okByRow(bl ? 1 : 0);
	}

	/**
	 * 获取农场的饲料和鸡蛋的出入记录详细信息
	 */
	@ApiOperation("获取农场的饲料和鸡蛋的出入记录详细信息")
	@PreAuthorize("@pms.hasPermission('module:feedrecord:query')")
	@GetMapping("/eggNum")
	public List eggNum(@Validated FarmFeedRecord farmFeedRecord) {
		QueryWrapper<FarmFeedRecord> qw=new QueryWrapper<>();
		if(StrUtil.isNotEmpty(farmFeedRecord.getBeginDate())){
			qw.between("create_time",farmFeedRecord.getBeginDate() + " 00:00:00",farmFeedRecord.getEndDate() + " 23:59:59");
		}
		TableDataInfo<FarmFeedRecord> td = PageUtils.buildDataInfo(farmFeedRecordService.page(PageUtils.buildPage(),qw));
		List<FarmFeedRecord> list = td.getData();
		Integer eggSettlementPeopleNum=0;
		Integer eggSettlementNum=0;
		Integer eggNum=0;
		for (FarmFeedRecord list1:list){
			if (list1.getFromType()==8){
				eggSettlementPeopleNum+=1;
				eggSettlementNum+=list1.getCount();
			}else if (list1.getFromType()==5){
				eggNum+=1;
			}
		}
		List<Integer> list2 = new ArrayList<>();
		list2.add(eggSettlementPeopleNum);
		list2.add(eggSettlementNum);
		list2.add(eggNum);
		return list2;
	}
}
